from flask import Blueprint, render_template, request, jsonify, url_for, redirect
from flask_login import login_required, login_user, current_user, logout_user, user_loaded_from_cookie
from app.forms import LoginForm, AddAdminForm
from app.models import Admin, Role
from app.utils import create_password, create_nonce_str
from datetime import datetime
from app.config import website_config

admin_controller = Blueprint("admin", __name__)

@admin_controller.route('/index', methods=["GET"])
@login_required
def index():
    return render_template("admin/index.html")

@admin_controller.route('/add', methods=["GET", "POST"])
@login_required
def add():
    form = AddAdminForm()
    if request.method == "POST":
        if form.validate_on_submit():
            role_id = form.role_id.data
            username = form.username.data
            password = form.password.data
            status = request.form.get('status', 1,type=int)
            salt = create_nonce_str()
            pwd = create_password(password, salt)
            admin = Admin(role_id=role_id, username=username,password=pwd, salt=salt, status=status)
            Admin.add_admin(admin)
            return jsonify({"code": 1, "msg": "添加成功"})
        else:
            return jsonify({"code": 0, "msg": "添加失败 - " + str(form.errors)})
        
    roles = Role.get_roles()
    return render_template("admin/add.html", roles=roles, form=form)

@admin_controller.route('/edit', methods=["GET", "POST"])
@login_required
def edit():
    form = AddAdminForm()
    id = request.args.get('id', 0, type=int)
    print("id = " + str(id))
    admin = Admin.get_user(id)
    if request.method == "POST":
        if id == website_config.get("admin_id"):
            return jsonify({"code": 0, "msg": "超级管理员不能修改"})
        if form.validate_on_submit():
            role_id = form.role_id.data
            username = form.username.data
            password = form.password.data
            status = request.form.get('status', 1,type=int)

            admin.role_id = role_id
            admin.username = username
            admin.status = status
            salt = create_nonce_str(6)
            pwd = create_password(password, salt)
            admin.salt = salt
            admin.passowrd = pwd
            Admin.update_admin()
            return jsonify({"code": 1, "msg": "修改成功"})
        else:
            return jsonify({"code": 0, "msg": "修改失败 - " + str(form.errors)})
        
    roles = Role.get_roles()
    return render_template("admin/edit.html", roles=roles, form=form, admin=admin)

@admin_controller.route('/lst', methods=["GET"])
@login_required
def look():
    page = request.args.get('page', 1, type = int)
    limit = request.args.get('limit', 10, type = int)
    keyword = request.args.get('keyword', '', type=str)
    pagination = Admin.get_users_page(keyword, page, limit)
    admins = pagination.items
    return jsonify({"code": 0, "msg": "获取成功", "data": [admin.to_json() for admin in admins], "count": pagination.total})

@admin_controller.route('/check', methods=["GET"])
@login_required
def check():
    username = request.args.get('name')
    old_username = request.args.get('old_username')
    if old_username and username != old_username:
        if Admin.get_user_by_username(username):
            return jsonify({"code": 1, "msg": "用户名已经存在"})
    return jsonify({"code": 0})

@admin_controller.route('/delete_op', methods=["POST"])
@login_required
def delete_op():
    id = request.form.get("id", 0, type=str).split(",")
    result = Admin.delete_user_by_id(id)
    if result:
        return jsonify({"code": 1, "msg": "删除成功"})
    return jsonify({"code": 0, "msg": "超级管理员不能删除"})

@admin_controller.route('/info', methods=["GET"])
@login_required
def info():

    return "info"

@admin_controller.route("/login", methods = ["GET"])
def login():
    form = LoginForm()
    return render_template("login.html", form = form)


@admin_controller.route("/dologin", methods=["POST"])
def do_login():
    form = LoginForm()
    if form.validate_on_submit():
        # 开始登录
        username = form.username.data.strip()
        password = form.password.data.strip()
        is_member = request.form.get("is_member", 0, type=int)
        user = Admin.get_user_by_username(username)
        if user is None or create_password(password, user.salt) != user.password:
            return jsonify({"code": 0, "msg": "用户名或密码不正确"})
        else:
            login_user(user, remember=lambda is_member : is_member==1)
            # 修改用户登录
            user.last_login_entered = user.login_entered
            user.login_entered = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            user.login_ip = request.remote_addr
            user.times = user.times + 1
            Admin.update_admin()
            return jsonify({"code": 1, "msg": "登录成功", "url": url_for("index.index")})
    return jsonify({"code": -1, "msg": "登录失败 - " + str(form.errors)})


@admin_controller.route('/logout', methods=["GET"])
@login_required
def logout():
    logout_user()
    return redirect(url_for('admin.login'))